package com.yedean.factory.support;

import cn.hutool.core.util.ClassUtil;
import com.yedean.factory.ConfigurableBeanFactory;
import com.yedean.factory.FactoryBean;
import com.yedean.factory.config.BeanDefinition;
import com.yedean.factory.config.BeanPostProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yedean
 * @date 2022/6/28
 */

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    private ClassLoader beanClassLoader = ClassUtil.getClassLoader();

    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    @Override
    public Object getBean(String name, Object... args) {
        return doGetBean(name, args);
    }

    @Override
    public Object getBean(String name) {
        return doGetBean(name, null);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType)  {
        return (T) getBean(name);
    }

    public Object doGetBean(String name, Object[] args) {
        //定义模板方法
        //1.先从单例缓存中取值
        Object sharedInstance = getSingleton(name);
        
        if (sharedInstance != null) {
            return getObjectForBeanInstance(sharedInstance, name);
        }

        BeanDefinition beanDefinition = getBeanDefinition(name);
        Object bean = createBean(name, beanDefinition, args);
        return getObjectForBeanInstance(bean, name);
    }


    private Object getObjectForBeanInstance(Object beanInstance, String beanName) {

        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        Object object = getCacheObjectForFactoryBean(beanName);

        if (object == null) {
            object = getObjectFromFactoryBean((FactoryBean<?>) beanInstance, beanName);
        }

        return object;
    }


    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        beanPostProcessors.remove(beanPostProcessor);
        beanPostProcessors.add(beanPostProcessor);
    }


    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }

    /**
     * 获取bean定义信息
     *
     * @param name beanName
     * @return BeanDefinition
     */
    protected abstract BeanDefinition getBeanDefinition(String name);

    /**
     * 创建bean实例
     *
     * @param name       名称
     * @param definition 定义信息
     * @param args       参数
     * @return bean实例
     */
    protected abstract Object createBean(String name, BeanDefinition definition, Object[] args);


    public ClassLoader getBeanClassLoader() {
        return this.beanClassLoader;
    }
}
